package com.whm.hrmanagement.service.impl;

import java.math.BigDecimal;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whm.common.core.domain.model.LoginUser;
import com.whm.common.enums.DeductEnum;
import com.whm.common.enums.OaStaffAttendanceEnum;
import com.whm.common.utils.DateUtils;
import com.whm.hrmanagement.domain.OaSalaryDeduct;
import com.whm.hrmanagement.domain.OaZrsglryda;
import com.whm.hrmanagement.domain.dto.OaStaffSalaryDto;
import com.whm.hrmanagement.domain.vo.OaSalaryVo;
import com.whm.hrmanagement.mapper.OaStaffAttendanceMapper;
import com.whm.hrmanagement.service.IOaSalaryDeductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import com.whm.hrmanagement.mapper.OaSalaryMapper;
import com.whm.hrmanagement.domain.OaSalary;
import com.whm.hrmanagement.service.IOaSalaryService;

import static com.whm.common.utils.PageUtils.startPage;

/**
 * 员工工资Service业务层处理
 * 
 * @author whm
 * @date 2024-02-07
 */
@Service
public class OaSalaryServiceImpl extends ServiceImpl<OaSalaryMapper, OaSalary>  implements IOaSalaryService
{
    @Autowired
    private OaSalaryMapper oaSalaryMapper;

    @Autowired
    private IOaSalaryDeductService iOaSalaryDeductService;


    @Autowired
    private OaStaffAttendanceMapper oaStaffAttendanceMapper;
    @Autowired
    private IOaSalaryService iOaSalaryService;
    /**
     * 查询员工工资
     * 
     * @param id 员工工资主键
     * @return 员工工资
     */
    @Override
    public OaSalary selectOaSalaryById(String id)
    {
        return oaSalaryMapper.selectOaSalaryById(id);
    }

    /**
     * 查询员工工资列表
     * 
     * @param oaSalary 员工工资
     * @return 员工工资
     */
    @Override
    public List<OaSalary> selectOaSalaryList(OaSalary oaSalary)
    {

       return oaSalaryMapper.selectOaSalaryList(oaSalary);
    }

    @Override
    public List<OaStaffSalaryDto> selectOaSalaryList2(OaSalaryVo oaSalaryVo) {
        String name =oaSalaryVo.getStaffName();
        String month =oaSalaryVo.getMonth();
        if (name == null) {
            name = "";
        }
        List<OaStaffSalaryDto> staffSalaryDtos = new ArrayList<>();
        if (oaSalaryVo.getDeptId() == null) {
            staffSalaryDtos = this.oaSalaryMapper.listStaffSalaryVO(name);
        }else {
            staffSalaryDtos = this.oaSalaryMapper.listStaffDeptSalaryVO( name, oaSalaryVo.getDeptId());
        }

        if (month == null) {
            Date datetime = new Date(System.currentTimeMillis());
            month = DateUtil.format(datetime, "yyyyMM");
        }
        LoginUser user = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user.getDeptId() != 204 && user.getDeptId() != 200 &&  user.getUserId() != 109 && user.getUserId() != 1) {


            return staffSalaryDtos.stream().filter(e -> e.getStaffId() == user.getUserId()).collect(Collectors.toList());
        }
        startPage();
        setSalaryInfo(month, staffSalaryDtos);

        return staffSalaryDtos;
    }



    private void setSalaryInfo(String month, List<OaStaffSalaryDto> list) {
        for (OaStaffSalaryDto oaStaffSalaryDto : list) {
            // 迟到扣款
            BigDecimal lateDeduct = BigDecimal.valueOf(this.oaStaffAttendanceMapper.countTimes(oaStaffSalaryDto.getStaffId(),
                    OaStaffAttendanceEnum.LATE.getCode(), month) * getPerLateDeduct(oaStaffSalaryDto));
            oaStaffSalaryDto.setLateDeduct(lateDeduct);
            // 早退扣款
            BigDecimal leaveEarlyDeduct = BigDecimal.valueOf(this.oaStaffAttendanceMapper.countTimes(oaStaffSalaryDto.getStaffId(),
                    OaStaffAttendanceEnum.LEAVE_EARLY.getCode(), month) * getPerLeaveEarlyDeduct(oaStaffSalaryDto));
            oaStaffSalaryDto.setLeaveEarlyDeduct(leaveEarlyDeduct);
            // 旷工扣款
            // 旷工扣款
            BigDecimal absenteeismDeduct = BigDecimal.valueOf(this.oaStaffAttendanceMapper.countTimes(oaStaffSalaryDto.getStaffId(),
                    OaStaffAttendanceEnum.ABSENTEEISM.getCode(), month) * getPerAbsenteeismDeduct(oaStaffSalaryDto));
            oaStaffSalaryDto.setAbsenteeismDeduct(absenteeismDeduct);
            // 休假扣款
            List<Date> leaveDateList = this.oaStaffAttendanceMapper.findLeaveDate(oaStaffSalaryDto.getStaffId(),
                    OaStaffAttendanceEnum.LEAVE.getCode(), month);
            oaStaffSalaryDto.setMonth(month);
            int count = 0;
            for (Date date : leaveDateList) {
                // 不包括周末
                if (!DateUtil.isWeekend(date)) {
                    count++;
                }
            }
            BigDecimal leaveDeduct = (BigDecimal.valueOf(count * getPerLeaveDeduct(oaStaffSalaryDto)));
            oaStaffSalaryDto.setLeaveDeduct(leaveDeduct);
            QueryWrapper<OaSalary> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("staff_id", oaStaffSalaryDto.getStaffId()).eq("month", month);
            OaSalary one = getOne(queryWrapper);
            if (one != null) {
                oaStaffSalaryDto
                        .setSalaryId(one.getId())
                        .setBaseSalary(one.getBaseSalary())
                        .setSubsidy(one.getSubsidy())
                        .setBonus(one.getBonus())
                        .setRemark(one.getRemark())
                        .setTotalSalary(one.getBaseSalary()
                                .add(one.getBonus())
                                .add(one.getSubsidy())
                                .subtract(lateDeduct)
                                .subtract(leaveEarlyDeduct)
                                .subtract(absenteeismDeduct)
                                .subtract(leaveDeduct)
                                .subtract(oaStaffSalaryDto.getSocialPay())
                                .subtract(oaStaffSalaryDto.getHousePay()));
            }
        }
    }


    public Integer getPerLateDeduct(OaStaffSalaryDto oaStaffSalaryDto) {
        QueryWrapper<OaSalaryDeduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id", oaStaffSalaryDto.getDeptId()).eq("type_num", DeductEnum.LATE_DEDUCT.getCode());
        OaSalaryDeduct oaSalaryDeduct = this.iOaSalaryDeductService.getOne(queryWrapper);
        return oaSalaryDeduct != null ? oaSalaryDeduct.getDeduct() : DeductEnum.LATE_DEDUCT.getDefaultValue();
    }

    /**
     * 每次早退扣款
     *
     * @param staffSalaryVO
     * @return
     */
    public Integer getPerLeaveEarlyDeduct(OaStaffSalaryDto oaStaffSalaryDto) {
        QueryWrapper<OaSalaryDeduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id", oaStaffSalaryDto.getDeptId()).eq("type_num", DeductEnum.LEAVE_EARLY_DEDUCT.getCode());
        OaSalaryDeduct oaSalaryDeduct = this.iOaSalaryDeductService.getOne(queryWrapper);
        return oaSalaryDeduct != null ? oaSalaryDeduct.getDeduct() : DeductEnum.LEAVE_EARLY_DEDUCT.getDefaultValue();
    }

    /**
     * 每次旷工扣款
     *
     * @param staffSalaryVO
     * @return
     */
    public Integer getPerAbsenteeismDeduct(OaStaffSalaryDto oaStaffSalaryDto) {
        QueryWrapper<OaSalaryDeduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id", oaStaffSalaryDto.getDeptId()).eq("type_num", DeductEnum.ABSENTEEISM_DEDUCT.getCode());
        OaSalaryDeduct salaryDeduct = this.iOaSalaryDeductService.getOne(queryWrapper);
        return salaryDeduct != null ? salaryDeduct.getDeduct() : DeductEnum.ABSENTEEISM_DEDUCT.getDefaultValue();
    }

    /**
     * 每次休假扣款
     *
     * @param staffSalaryVO
     * @return
     */
    public Integer getPerLeaveDeduct(OaStaffSalaryDto oaStaffSalaryDto) {
        QueryWrapper<OaSalaryDeduct> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept_id", oaStaffSalaryDto.getDeptId()).eq("type_num", DeductEnum.LEAVE_DEDUCT.getCode());
        OaSalaryDeduct salaryDeduct = this.iOaSalaryDeductService.getOne(queryWrapper);
        return salaryDeduct != null ? salaryDeduct.getDeduct() : DeductEnum.LEAVE_DEDUCT.getDefaultValue();
    }







    /**
     * 新增员工工资
     * 
     * @param oaSalary 员工工资
     * @return 结果
     */
    @Override
    public int insertOaSalary(OaSalary oaSalary)
    {
        oaSalary.setCreateTime(DateUtils.getNowDate());
        return oaSalaryMapper.insertOaSalary(oaSalary);
    }

    /**
     * 修改员工工资
     * 
     * @param oaSalary 员工工资
     * @return 结果
     */
    @Override
    public boolean updateOaSalary(OaSalary oaSalary)
    {
        oaSalary.setUpdateTime(DateUtils.getNowDate());

        QueryWrapper<OaSalary> query = new QueryWrapper<>();
        query.eq("month", oaSalary.getMonth()).eq("staff_id", oaSalary.getStaffId());




        return   saveOrUpdate(oaSalary, query);
    }

    /**
     * 批量删除员工工资
     * 
     * @param ids 需要删除的员工工资主键
     * @return 结果
     */
    @Override
    public int deleteOaSalaryByIds(String[] ids)
    {
        return oaSalaryMapper.deleteOaSalaryByIds(ids);
    }

    /**
     * 删除员工工资信息
     * 
     * @param id 员工工资主键
     * @return 结果
     */
    @Override
    public int deleteOaSalaryById(String id)
    {
        return oaSalaryMapper.deleteOaSalaryById(id);
    }
}
